package cn.hn.java.summer.mvc.tag;

import cn.hn.java.summer.mvc.WebContext;
import org.rythmengine.template.JavaTagBase;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.resource.ResourceUrlProvider;

import javax.servlet.http.HttpServletRequest;

@Component
public class ResourceTag extends JavaTagBase implements ApplicationContextAware
{
  public String __getName()
  {
    return "res";
  }

  private static ResourceUrlProvider resourceUrlProvider;

  protected void call(__ParameterList params, __Body body)
  {
    Object obj = params.getDefault();
    HttpServletRequest request = WebContext.getRequest();
    String contextPath = request.getContextPath();

    if ((obj != null) && ((obj instanceof String))){
      String url = (String)obj;
      url=resourceUrlProvider.getForLookupPath(url);
      if ((url.startsWith("http")) || (url.startsWith("//"))) {
        p(url);
      }else{
        p(contextPath + url);
      }
    }
  }

  @Override
  public void setApplicationContext(ApplicationContext context) throws BeansException {
    if(resourceUrlProvider==null){
      resourceUrlProvider=BeanFactoryUtils.beanOfTypeIncludingAncestors(context, ResourceUrlProvider.class, true, false);
    }
  }
}